// 标签管理模块
const { DatabaseManager } = require('./database')
const tagCategories = require('./tag_categories_rows.json')
const tags = require('./tags_rows.json')

class TagManager {
  constructor() {
    this.db = new DatabaseManager()
  }

  // 创建所有标签（分类和标签）
  async createAllTags() {
    console.log('🏷️  开始创建标签系统...')
    
    // 1. 创建标签分类
    const categories = await this.createTagCategories()
    
    if (categories.length === 0) {
      console.error('❌ 没有成功创建任何标签分类')
      return { categories: [], tags: [] }
    }
    
    // 2. 创建标签
    const tagList = await this.createTags()
    
    console.log(`\n📊 标签系统创建完成:`)
    console.log(`   - 分类: ${categories.length} 个`)
    console.log(`   - 标签: ${tagList.length} 个`)
    
    return {
      categories,
      tags: tagList
    }
  }

  // 创建标签分类
  async createTagCategories() {
    console.log('📂 创建标签分类...')
    
    const createdCategories = []
    
    for (const categoryData of tagCategories) {
      try {
        // 检查分类是否已存在
        const { data: existingCategory, error: checkError } = await this.db.supabase
          .from('tag_categories')
          .select('*')
          .eq('name', categoryData.name)
          .single()
        
        let category = null
        
        if (existingCategory && !checkError) {
          // 分类已存在，更新信息
          const { data: updatedCategory, error: updateError } = await this.db.supabase
            .from('tag_categories')
            .update({
              display_name: categoryData.display_name,
              description: categoryData.description,
              sort_order: categoryData.sort_order,
              is_active: categoryData.is_active
            })
            .eq('name', categoryData.name)
            .select()
            .single()
          
          if (updateError) {
            console.error(`❌ 更新标签分类 ${categoryData.name} 失败:`, updateError)
            continue
          }
          
          category = updatedCategory
          console.log(`📝 更新标签分类: ${categoryData.display_name}`)
        } else {
          // 创建新分类
          const { data: newCategory, error: insertError } = await this.db.supabase
            .from('tag_categories')
            .insert({
              name: categoryData.name,
              display_name: categoryData.display_name,
              description: categoryData.description,
              sort_order: categoryData.sort_order,
              is_active: categoryData.is_active
            })
            .select()
            .single()
          
          if (insertError) {
            console.error(`❌ 创建标签分类 ${categoryData.name} 失败:`, insertError)
            continue
          }
          
          category = newCategory
          console.log(`✅ 成功创建标签分类: ${categoryData.display_name}`)
        }
        
        createdCategories.push(category)
        
      } catch (error) {
        console.error(`❌ 处理标签分类 ${categoryData.name} 时发生错误:`, error)
      }
    }
    
    console.log(`📊 标签分类处理完成: ${createdCategories.length}/${tagCategories.length} 个分类`)
    return createdCategories
  }

  // 创建标签
  async createTags() {
    console.log('🏷️  创建标签...')
    
    const createdTags = []
    
    // 首先获取所有分类的映射关系
    const { data: categories, error: categoriesError } = await this.db.supabase
      .from('tag_categories')
      .select('id, name')
    
    if (categoriesError) {
      console.error('❌ 获取标签分类失败:', categoriesError)
      return []
    }
    
    // 创建分类名称到ID的映射
    const categoryMap = {}
    categories.forEach(cat => {
      categoryMap[cat.name] = cat.id
    })
    
    for (const tagData of tags) {
      try {
        // 根据JSON中的category_id找到对应的分类名称
        let categoryName = null
        if (tagData.category_id === 1) categoryName = 'genre'
        else if (tagData.category_id === 2) categoryName = 'universe'
        else if (tagData.category_id === 3) categoryName = 'language'
        else if (tagData.category_id === 4) categoryName = 'country'
        
        if (!categoryName || !categoryMap[categoryName]) {
          console.error(`❌ 无法找到分类 ${tagData.category_id} 对应的分类名称或数据库ID`)
          continue
        }
        
        const actualCategoryId = categoryMap[categoryName]
        
        // 检查标签是否已存在
        const { data: existingTag, error: checkError } = await this.db.supabase
          .from('tags')
          .select('*')
          .eq('name', tagData.name)
          .eq('category_id', actualCategoryId)
          .single()
        
        let tag = null
        
        if (existingTag && !checkError) {
          // 标签已存在，更新信息
          const { data: updatedTag, error: updateError } = await this.db.supabase
            .from('tags')
            .update({
              display_name: tagData.display_name,
              description: tagData.description,
              color: tagData.color,
              sort_order: tagData.sort_order,
              is_active: tagData.is_active,
              usage_count: tagData.usage_count
            })
            .eq('name', tagData.name)
            .eq('category_id', actualCategoryId)
            .select()
            .single()
          
          if (updateError) {
            console.error(`❌ 更新标签 ${tagData.name} 失败:`, updateError)
            continue
          }
          
          tag = updatedTag
          console.log(`📝 更新标签: ${tagData.display_name}`)
        } else {
          // 创建新标签 - 不指定id，让数据库自动生成
          const { data: newTag, error: insertError } = await this.db.supabase
            .from('tags')
            .insert({
              category_id: actualCategoryId,
              name: tagData.name,
              display_name: tagData.display_name,
              description: tagData.description,
              color: tagData.color,
              sort_order: tagData.sort_order,
              is_active: tagData.is_active,
              usage_count: tagData.usage_count
            })
            .select()
            .single()
          
          if (insertError) {
            console.error(`❌ 创建标签 ${tagData.name} 失败:`, insertError)
            continue
          }
          
          tag = newTag
          console.log(`✅ 成功创建标签: ${tagData.display_name}`)
        }
        
        createdTags.push(tag)
        
      } catch (error) {
        console.error(`❌ 处理标签 ${tagData.name} 时发生错误:`, error)
      }
    }
    
    console.log(`📊 标签处理完成: ${createdTags.length}/${tags.length} 个标签`)
    return createdTags
  }

  // 获取标签统计信息
  async getTagStats() {
    try {
      const [categoryStats, tagStats] = await Promise.all([
        this.db.supabase
          .from('tag_categories')
          .select('is_active'),
        this.db.supabase
          .from('tags')
          .select('is_active, usage_count')
      ])
      
      if (categoryStats.error) {
        throw categoryStats.error
      }
      
      if (tagStats.error) {
        throw tagStats.error
      }
      
      const categories = categoryStats.data
      const tags = tagStats.data
      
      const totalCategories = categories.length
      const activeCategories = categories.filter(c => c.is_active).length
      
      const totalTags = tags.length
      const activeTags = tags.filter(t => t.is_active).length
      const totalUsage = tags.reduce((sum, tag) => sum + (tag.usage_count || 0), 0)
      
      return {
        success: true,
        stats: {
          categories: {
            total: totalCategories,
            active: activeCategories
          },
          tags: {
            total: totalTags,
            active: activeTags,
            totalUsage
          }
        }
      }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 清空所有标签
  async clearAllTags() {
    console.log('🗑️  开始清空所有标签...')
    
    try {
      // 先清空电影标签关联
      const { error: movieTagsError } = await this.db.supabase
        .from('movie_tags')
        .delete()
        .neq('id', 0)
      
      if (movieTagsError) {
        console.error('❌ 清空电影标签关联失败:', movieTagsError)
      } else {
        console.log('✅ 电影标签关联已清空')
      }
      
      // 清空标签
      const { error: tagsError } = await this.db.supabase
        .from('tags')
        .delete()
        .neq('id', 0)
      
      if (tagsError) {
        console.error('❌ 清空标签失败:', tagsError)
      } else {
        console.log('✅ 标签已清空')
      }
      
      // 清空标签分类
      const { error: categoriesError } = await this.db.supabase
        .from('tag_categories')
        .delete()
        .neq('id', 0)
      
      if (categoriesError) {
        console.error('❌ 清空标签分类失败:', categoriesError)
      } else {
        console.log('✅ 标签分类已清空')
      }
      
      console.log('📊 标签系统清空完成')
      return { success: true, message: '标签系统已清空' }
    } catch (error) {
      console.error('❌ 清空标签时发生错误:', error)
      return { success: false, error: error.message }
    }
  }
}

module.exports = TagManager
